﻿using System;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Collections;

namespace Extractor.LibCode
{
    public class cDBHelper : cDBService
    {
        public cDBHelper()
        {

        }

        public bool genidStepDown(string IDName)
        {
            try
            {
                string sSql = "update sy_genid set icurr=icurr-istep where genid='" + IDName + "'";
                if (Dbserver.openConn())
                {
                    Dbserver.ExecuteNonQuery(sSql);
                    return true;
                }
                else
                {
                    throw new Exception("IDName Could not be found");
                }
            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }
        }
        public bool genidStepUP(string IDName)
        {
            try
            {
                string sSql = "update sy_genid set icurr=icurr+istep where genid='" + IDName + "'";
                if (Dbserver.openConn())
                {
                    Dbserver.ExecuteNonQuery(sSql);
                    Dbserver.CommitAndCloseConn();
                    return true;
                }
                else
                {
                    throw new Exception("IDName Could not be found");
                }
            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }
        }

        public string genIDCommit(string IDName)
        {
            string sid = genId(IDName);
            genidStepUP(IDName);
            return sid;
        }
        public string genId(string IDName)
        {
            try
            {
                DataTable dt = new DataTable();
                string sql = "select * from sy_genid where genid='" + IDName + "'";
                dt = Dbserver.ExecuteQuery(sql, "genid");
                if (dt.Rows.Count > 0)
                {

                    Int32 icurr = (Int32)dt.Rows[0]["icurr"];
                    Int32 imin = (Int32)dt.Rows[0]["imin"];
                    Int64 imax = Int64.Parse(dt.Rows[0]["imax"].ToString());
                    int istep = (int)dt.Rows[0]["istep"];
                    string prefix = dt.Rows[0]["prefix"].ToString();
                    string sufix = dt.Rows[0]["sufix"].ToString();
                    string smax = imax.ToString();
                    int l = smax.Length;
                    return prefix.Trim() + (icurr + istep).ToString().PadLeft(l, '0') + sufix.ToString();

                }
                else
                {
                    throw new Exception("IDName Could not be found");
                }


            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }
        }

    }
}